package com.ruoyi.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.business.domain.FilePerson;
import com.ruoyi.business.domain.bo.FileExternalUnitsFormPersonBo;
import com.ruoyi.business.domain.bo.FileInternalTransferInPersonBo;
import com.ruoyi.business.mapper.FilePersonMapper;
import com.ruoyi.business.service.IFileExternalUnitsFormPersonService;
import com.ruoyi.business.service.IFileInternalTransferInPersonService;
import com.ruoyi.business.service.IFilePersonService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.DataBaseHelper;
import com.ruoyi.common.utils.DateExtUtils;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 人员管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-11
 */
@Service
public class FilePersonServiceImpl implements IFilePersonService {
    @Autowired
    private FilePersonMapper filePersonMapper;
    @Autowired
    private IFileExternalUnitsFormPersonService fileExternalUnitsFormPersonService;
    @Autowired
    private IFileInternalTransferInPersonService fileInternalTransferInPersonService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysPostMapper sysPostMapper;


    /**
     * 查询人员管理
     *
     * @param id 人员管理ID
     * @return 人员管理
     */
    @Override
    public FilePerson selectFilePersonById(Long id) {
        return filePersonMapper.selectFilePersonById(id);
    }

    @Override
    public FilePerson selectFilePersonByCode(String code) {
        return filePersonMapper.selectOne(new QueryWrapper<FilePerson>().eq("code", code));
    }

    /**
     * 查询人员管理列表
     *
     * @param filePerson 人员管理
     * @return 人员管理
     */
    @Override
    public List<FilePerson> selectFilePersonList(FilePerson filePerson) {
        return filePersonMapper.selectFilePersonList(filePerson);
    }

    @Override
    public TableDataInfo<FilePerson> selectPageFilePersonList(FilePerson filePerson, PageQuery pageQuery) {
        Page<FilePerson> FilePerson = filePersonMapper.selectJoinPage(pageQuery.build(), FilePerson.class, this.buildQueryWrapper(filePerson));
        return TableDataInfo.build(FilePerson);
    }

    @Override
    public TableDataInfo<FilePerson> selectPersonListByFromId(FilePerson filePerson, PageQuery pageQuery) {
        FileExternalUnitsFormPersonBo beanBo = new FileExternalUnitsFormPersonBo();
        beanBo.setFormId(filePerson.getFromId());
        List<Long> personIds = fileExternalUnitsFormPersonService.queryByFromId(beanBo);
        if (personIds.size() == 0) {
            return null;
        } else {
            List<FilePerson> filePeople = filePersonMapper.selectJoinList(FilePerson.class, this.buildQueryWrapper(filePerson).in(!personIds.isEmpty(), FilePerson::getId, personIds));
            return TableDataInfo.build(filePeople);
        }
    }

    @Override
    public TableDataInfo<FilePerson> selectPersonListByInId(FilePerson filePerson, PageQuery pageQuery) {
        FileInternalTransferInPersonBo beanBo = new FileInternalTransferInPersonBo();
        beanBo.setInId(filePerson.getInId());
        List<Long> personIds = fileInternalTransferInPersonService.queryByInId(beanBo);
        if (personIds.size() == 0) {
            return null;
        } else {
            List<FilePerson> filePeople = filePersonMapper.selectJoinList(FilePerson.class, this.buildQueryWrapper(filePerson).in(!personIds.isEmpty(), FilePerson::getId, personIds));
            return TableDataInfo.build(filePeople);
        }
    }

    private MPJLambdaWrapper<FilePerson> buildQueryWrapper(FilePerson filePerson) {
        Map<String, Object> params = filePerson.getParams();
        MPJLambdaWrapper<FilePerson> filePersonJoinLambdaWrapper = new MPJLambdaWrapper<FilePerson>();
        filePersonJoinLambdaWrapper.selectAll(FilePerson.class)
                .selectAs(SysDept::getDeptName, FilePerson::getOrgName)
                .leftJoin(SysDept.class, SysDept::getDeptId, FilePerson::getOrgid)
                .like(StrUtil.isNotBlank(filePerson.getName()), FilePerson::getName, filePerson.getName())
                .like(StrUtil.isNotBlank(filePerson.getCode()), FilePerson::getCode, filePerson.getCode())
                .eq(BeanUtil.isNotEmpty(filePerson.getGender()), FilePerson::getGender, filePerson.getGender())
                .and(BeanUtil.isNotEmpty(filePerson.getOrgid()), wq -> wq.eq(FilePerson::getOrgid, filePerson.getOrgid())
                        .or().apply(DataBaseHelper.findInSet(filePerson.getOrgid(), "ancestors"))
                )
                .eq(BeanUtil.isNotEmpty(filePerson.getOffice()), FilePerson::getOffice, filePerson.getOffice())
                .eq(BeanUtil.isNotEmpty(filePerson.getJobTitle()), FilePerson::getJobTitle, filePerson.getJobTitle())
                .eq(BeanUtil.isNotEmpty(filePerson.getArchiveLocation()), FilePerson::getArchiveLocation, filePerson.getArchiveLocation())
                .eq(BeanUtil.isNotEmpty(filePerson.getSecretLevel()), FilePerson::getSecretLevel, filePerson.getSecretLevel());

        return filePersonJoinLambdaWrapper;
    }

    /**
     * 新增人员管理
     *
     * @param filePerson 人员管理
     * @return 结果
     */
    @Override
    public int insertFilePerson(FilePerson filePerson) {
        filePerson.setCreateTime(DateExtUtils.getNowDate());
        return filePersonMapper.insertFilePerson(filePerson);
    }

    @Override
    public int insertFromFilePerson(FilePerson filePerson) {
        filePerson.setCreateTime(DateExtUtils.getNowDate());
        filePerson.setId(IdUtil.getSnowflakeNextId());
        int flag = filePersonMapper.insertFilePerson(filePerson);

        // 新增外单位与人员关联表
        FileExternalUnitsFormPersonBo fromPersonBo = new FileExternalUnitsFormPersonBo();
        fromPersonBo.setId(IdUtil.getSnowflakeNextId());
        fromPersonBo.setFormId(filePerson.getFromId());
        fromPersonBo.setPersonId(filePerson.getId());
        fileExternalUnitsFormPersonService.insertByBo(fromPersonBo);

        return flag;
    }

    @Override
    public int insertInFilePerson(FilePerson filePerson) {
        filePerson.setCreateTime(DateExtUtils.getNowDate());
        filePerson.setId(IdUtil.getSnowflakeNextId());
        int flag = filePersonMapper.insertFilePerson(filePerson);

        // 新增本单位与人员关联表
        FileInternalTransferInPersonBo inPersonBo = new FileInternalTransferInPersonBo();
        inPersonBo.setId(IdUtil.getSnowflakeNextId());
        inPersonBo.setInId(filePerson.getInId());
        inPersonBo.setPersonId(filePerson.getId());
        fileInternalTransferInPersonService.insertByBo(inPersonBo);

        return flag;
    }

    /**
     * 修改人员管理
     *
     * @param filePerson 人员管理
     * @return 结果
     */
    @Override
    public int updateFilePerson(FilePerson filePerson) {
        filePerson.setUpdateTime(DateExtUtils.getNowDate());
        return filePersonMapper.updateFilePerson(filePerson);
    }

    /**
     * 批量删除人员管理
     *
     * @param ids 需要删除的人员管理ID
     * @return 结果
     */
    @Override
    public int deleteFilePersonByIds(Long[] ids) {
        for (Long id : ids) {
            fileExternalUnitsFormPersonService.deleteByPersonId(id);
            fileInternalTransferInPersonService.deleteByPersonId(id);
        }
        return filePersonMapper.deleteFilePersonByIds(ids);
    }

    /**
     * 删除人员管理信息
     *
     * @param id 人员管理ID
     * @return 结果
     */
    @Override
    public int deleteFilePersonById(Long id) {
        fileExternalUnitsFormPersonService.deleteByPersonId(id);
        fileInternalTransferInPersonService.deleteByPersonId(id);
        return filePersonMapper.deleteFilePersonById(id);
    }

    @Override
    public List<FilePerson> selectUserByIds(String ids) {
        if (StrUtil.isBlank(ids)) {
            return new ArrayList<>();
        } else {
            Long[] userIdArray = Arrays.stream(ids.split(","))
                    .map(Long::parseLong)
                    .distinct().toArray(Long[]::new);
            return filePersonMapper.selectUserByIds(userIdArray);
        }
    }

    private String getDictData(String label, String type) {
        QueryWrapper<SysDictData> dictDataQueryWrapper = new QueryWrapper<SysDictData>().eq("dict_label", label).eq("dict_type", type);
        SysDictData dictDateBean = sysDictDataMapper.selectOne(dictDataQueryWrapper);
        if (dictDateBean == null) {
            SysDictData sysDictData = new SysDictData();
            sysDictData.setDictType(type);
            sysDictData.setDictLabel(label);
            String value = String.valueOf(new Date().getTime());
            sysDictData.setDictValue(value);
//            sysDictData.setDictSort(new Date().getTime());
            sysDictData.setDictCode(IdUtil.getSnowflakeNextId());
            sysDictData.setStatus("0");
            sysDictData.setListClass("default");
            sysDictData.setIsDefault("N");
            boolean flag = sysDictDataMapper.insertOrUpdate(sysDictData);
            if (flag) {
                return sysDictData.getDictValue();
            }
        } else {
            return dictDateBean.getDictValue();
        }
        return null;
    }
}
